package com.ls.hnks.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ls.hnks.util.Result;
import com.ls.hnks.model.User;
import com.ls.hnks.model.UserGroup;
import com.ls.hnks.service.UserGroupService;
import com.ls.hnks.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@SaCheckLogin
@RestController
@RequestMapping("/group")
public class UserGroupController {

    @Autowired
    private UserGroupService userGroupService;

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public Result list() {
        QueryWrapper<UserGroup> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.orderByAsc("num");
        List<UserGroup> list = userGroupService.list(groupQueryWrapper);
        return Result.ok(list);
    }

    @PostMapping("/save")
    public Result save(@RequestBody UserGroup group){
        log.info("分组信息 --- {}", JSON.toJSONString(group));
        int createUserId = Integer.parseInt(StpUtil.getLoginId().toString());
        group.setCreateuserid(createUserId);
        userGroupService.saveOrUpdate(group);
        return Result.ok();
    }

    @PostMapping("/remove/{id}")
    public Result remove( @PathVariable String id){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("groupId",id);
        int count = userService.count(userQueryWrapper);
        if (count > 1) {
            return Result.fail().message("操作失败，小组中还有成员!");
        }
        userGroupService.removeById(id);
        return Result.ok();
    }
}
